const fs = require('fs')
const autoprefixer = require('autoprefixer');
const pxtorem = require('postcss-pxtorem');
const path = require('path');
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const productionGzipExtensions = ['js', 'css'];


function resolve(dir) {
  return path.join(__dirname, dir)
}
const Timestamp = new Date().getTime();
module.exports = {
  lintOnSave: true,
  outputDir: 'dist',
  publicPath: '/',
  css: {
    loaderOptions: {
      postcss: {
        plugins: [
          autoprefixer(),
          pxtorem({
            rootValue: 37.5,
            propList: ['*']
          })
        ]
      }
    }
  },
  devServer: {
    host: '0.0.0.0',
    port: 3001,
    proxy: {
      '/mock': {
        target: 'https://www.easy-mock.com/mock/5d6c9459cb03594446dd4d3c/yyz',
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/mock': ''
        }
      }
    }
  },
  chainWebpack: (config) => {
    // 修复HMR
    config.resolve.symlinks(true);
    // 别名配置
    config.resolve.alias
      .set('@a', resolve('src/asset'))
      .set('@c', resolve('src/component'))
      .set('@p', resolve('public'))
  },
  configureWebpack: (config) => {
    config.plugins.push({
      apply: (compiler) => {
        compiler.hooks.done.tap('SomePlugin', compilation => {
          // 自动生成打包版本号
          const version = new Date().getTime()
          const content = "getVersion('" + version + "')";
          fs.writeFile(path.resolve(__dirname, './dist/') + "/version.js", content, function(err) {
            if (err) {
              return console.log(err);
            }
            console.log("版本号："+version);
          });
        });
      }
    })
    Object.assign(config, {
      // 开发生产共同配置
      plugins: [
        ...config.plugins,
        new CompressionWebpackPlugin({
          algorithm: 'gzip',
          test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
          threshold: 10240,
          minRatio: 0.8
        })
      ],
      output: { // js添加时间戳
        ...config.output,
        filename: `js/[name].${Timestamp}.js`,
        chunkFilename: `js/[name].${Timestamp}.js`,
      },
    })
  }
};

